package cn.com.nes.site.module.service;

import cn.com.nes.common.util.MapUtil;
import cn.com.nes.common.util.OssUtil;
import cn.com.nes.common.util.TianyanchaCrawler;
import cn.com.nes.common.util.TianyanchaNew;
import cn.com.nes.site.entity.DataReq;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.module.dao.CompanyDaoImpl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class CompanyService {

    @Resource
    private CompanyDaoImpl impl;

    public PageData getCompaniesAroundTheCoordinates(DataReq req) {
        PageData res = new PageData();
        res.setRetCode(0);
        Map<String, Object> respMap = new LinkedHashMap<String, Object>();
        res.setData(respMap);

        String latitude = (String) req.getReqData().get("latitude");
        String longitude = (String) req.getReqData().get("longitude");
        String pageId = (String) req.getReqData().get("pageid");

        JSONObject cityInfo = MapUtil.getCityName(String.valueOf(longitude), String.valueOf(latitude));
        if (cityInfo == null) {
            return res;
        }

        String province = cityInfo.getString("province");
        String city = cityInfo.getString("city");
        String district = cityInfo.getString("district");

        StringBuilder keyword = new StringBuilder("热泵 ");
        keyword.append(province);
        if (!"[]".equals(city)) {
            keyword.append(city);
        }
        if (!"[]".equals(district)) {
            keyword.append(district);
        }

        StrUtil.isNotEmpty(keyword);
        final int pageNum = NumberUtil.isNumber(pageId) ? Integer.parseInt(pageId) : 1;
        final JSONArray companies = TianyanchaCrawler.searchCompanies(keyword.toString(), pageNum);

        List<Map<String, Object>> page = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < companies.size(); i++) {
            JSONObject company = companies.getJSONObject(i);
            Map<String, Object> map = new LinkedHashMap<String, Object>();
            for (String key : company.keySet()) {
                map.put(key, company.get(key));
            }
            page.add(map);
        }

        res.setPagecount(TianyanchaCrawler.getPageCount(keyword.toString()));
        res.setPagesize(20);
        res.setPageid(pageNum);
        res.setRecordcount(TianyanchaCrawler.getRecordCount(keyword.toString()));
        res.setPage(page);

        res.setRetCode(0);
        res.setRetMessage("OK");
        return res;
    }

    public PageData saveCompanyToExpand(DataReq req) {
        //根据地址获取行政区划代码
        final JSONObject geo = MapUtil.getGeoByAddress((String) req.getReqData().get("address"));
        if (geo != null) {
            String adcode = geo.getString("adcode");
            if (StrUtil.isNotEmpty(adcode)) {
                req.getReqData().put("areacode", adcode.substring(0, 6) + "000000");
            }
            String location = geo.getString("location");
            if (StrUtil.isNotEmpty(location)) {
                final String[] coordinates = location.split(",");
                req.getReqData().put("longitude", coordinates[0]);
                req.getReqData().put("latitude", coordinates[1]);
            }
        }
        return impl.saveCompanyToExpand(req);
    }

    public PageData getCompanyToExpand(DataReq req) {
        return impl.getCompanyToExpand(req);
    }

    public PageData getCompanyFlagMap(DataReq req) {
        return impl.getCompanyFlagMap(req);
    }

    public PageData convertToFormalCompany(DataReq req) {
        return impl.convertToFormalCompany(req);
    }

    public PageData submitCompanyInformation(DataReq req) {
        return impl.submitCompanyInformation(req);
    }

    public PageData getAgentIntentApplications(DataReq req) {
        return impl.getAgentIntentApplications(req);
    }

    public PageData auditAgentIntentApplication(DataReq req) {
        return impl.auditAgentIntentApplication(req);
    }

    public PageData editCompanyInformation(DataReq req) {
        return impl.editCompanyInformation(req);
    }

    public PageData getAllTargetCompany(DataReq req) {
        return impl.getAllTargetCompany(req);
    }

    public PageData saveCompanyPromotionCard(DataReq req) {
        return impl.saveCompanyPromotionCard(req);
    }

    public PageData savePromotionDisplay(DataReq req) {
        return impl.savePromotionDisplay(req);
    }

    public PageData savePromotionBannerDisplay(DataReq req) {
        return impl.savePromotionBannerDisplay(req);
    }

    public PageData auditCompanyPromotionCard(DataReq req) {
        return impl.auditCompanyPromotionCard(req);
    }

    public PageData getPromotionBanner(DataReq req) {
        final PageData promotionBanner = impl.getPromotionBanner(req);
        final List<Map<String, Object>> list = promotionBanner.getPage();
        for (Map<String, Object> map : list) {
            final String banner = map.get("banner").toString();
            String imgSignURL = "";
            if (StrUtil.isNotEmpty(banner)) {
                imgSignURL = OssUtil.getImgSignURL(banner, 0);
            }
            map.put("bannerURL", imgSignURL);
        }
        return promotionBanner;
    }

    public PageData getPromotionCards(DataReq req) {
        final PageData promotionCards = impl.getPromotionCards(req);
        final List<Map<String, Object>> list = promotionCards.getPage();
        for (Map<String, Object> map : list) {
            String poster = map.get("poster").toString();
            String posterURL = "";
            String logo = map.get("companyLogo").toString();
            String logoURL = "";
            if (StrUtil.isNotEmpty(poster)) {
                posterURL = OssUtil.getImgSignURL(poster, 0);
            }
            if (StrUtil.isNotEmpty(logo)) {
                logoURL = OssUtil.getImgSignURL(logo, 0);
            }
            map.put("posterURL", posterURL);
            map.put("logoURL", logoURL);
        }
        return promotionCards;
    }

    public PageData getPromotionCardByCompanyId(DataReq req) {
        final PageData promotionCards = impl.getPromotionCardByCompanyId(req);
        List<Map<String, Object>> list = promotionCards.getPage();
        if (CollUtil.isNotEmpty(list)) {
            for (Map<String, Object> map : list) {
                String poster = map.get("poster").toString();
                String posterURL = "";
                String logo = map.get("companyLogo").toString();
                String logoURL = "";
                if (StrUtil.isNotEmpty(poster)) {
                    posterURL = OssUtil.getImgSignURL(poster, 0);
                }
                if (StrUtil.isNotEmpty(logo)) {
                    logoURL = OssUtil.getImgSignURL(logo, 0);
                }
                map.put("posterURL", posterURL);
                map.put("logoURL", logoURL);
            }
        }
        return promotionCards;
    }

    public PageData getPromotionDisplayState(DataReq req) {
        return impl.getPromotionDisplayState(req);
    }

    public PageData saveCompanyPromotionBanner(DataReq req) {
        return impl.saveCompanyPromotionBanner(req);
    }

    public PageData removePromotionDisplay(DataReq req) {
        return impl.removePromotionDisplay(req);
    }

    public PageData getPromotionBannerByCompanyId(DataReq req) {
        final PageData promotionBanner = impl.getPromotionBannerByCompanyId(req);
        if (CollUtil.isNotEmpty(promotionBanner.getPage())) {
            final Map<String, Object> map = promotionBanner.getPage().get(0);
            final String banner = map.get("banner").toString();
            String imgSignURL = "";
            if (StrUtil.isNotEmpty(banner)) {
                imgSignURL = OssUtil.getImgSignURL(banner, 0);
            }
            map.put("bannerURL", imgSignURL);
        }
        return promotionBanner;
    }

    public PageData auditCompanyPromotionBanner(DataReq req) {
        return impl.auditCompanyPromotionBanner(req);
    }

    public PageData getCompanyInfo(DataReq req) {
        return impl.getCompanyInfo(req);
    }

    public PageData getCertificatedIDCardImageByCompanyId(DataReq req) {
        return impl.getCertificatedIDCardImageByCompanyId(req);
    }

    public PageData updateCompany(DataReq req) {
        return impl.updateCompany(req);
    }

    public PageData getCompanyAllList(DataReq req) {
        return impl.getCompanyAllList(req);
    }

    public PageData deleteAllCompany(String companyId) {
        return impl.deleteAllCompany(companyId);
    }

    public PageData getCompanyMap(DataReq req) throws SQLException {
        List<Map<String, Object>> page = new ArrayList<Map<String, Object>>();
        PageData res = new PageData();

        //根据经纬度获取城市信息
        String latitude = (String) req.getReqData().get("latitude");
        String longitude = (String) req.getReqData().get("longitude");
        String keyword = (String) req.getReqData().get("keyword");//前端查询条件
        String pageNum = (String) req.getReqData().get("pageNum");
        String pageSize = (String) req.getReqData().get("pageSize");

        //StringBuilder word = new StringBuilder("热泵");
        StringBuilder word = new StringBuilder();
        if (!latitude.equals("") && latitude != null) {
            JSONObject cityInfo = MapUtil.getCityName(String.valueOf(longitude), String.valueOf(latitude));
            //根据城市等关键字信息获取公司信息
            String province = cityInfo.getString("province");
            String city = cityInfo.getString("city");
            String district = cityInfo.getString("district");
            word.append(" ").append(province);
            if (!"[]".equals(city)) {
                word.append(" ").append(city);
            }
            word.append(" ").append(district);
        }

        if (!"".equals(keyword) && null != keyword) {
            word.append(" ").append(keyword);
        }
        System.out.println(word);

        final int pageNum0 = NumberUtil.isNumber(pageNum) ? Integer.parseInt(pageNum) : 1;
        final int pageSize0 = NumberUtil.isNumber(pageSize) ? Integer.parseInt(pageSize) : 20;
        JSONObject companyObj = TianyanchaNew.searchCompany(word.toString(), pageNum0, pageSize0);
        if (companyObj != null) {
            JSONArray companyArr = companyObj.getJSONArray("items");//详细信息
            //根据公司名称反查经纬度
            for (int i = 0; i < companyArr.size(); i++) {
                JSONObject geocode = (JSONObject) companyArr.get(i);
                JSONObject adressObj = MapUtil.getGeoByAddress(geocode.getString("name"));
                if (adressObj != null) {
                    String lng = adressObj.getString("lng");
                    String lat = adressObj.getString("lat");
                    adressObj.getString("formatted_address");
                    ((JSONObject) companyArr.get(i)).put("longitude", lng);
                    ((JSONObject) companyArr.get(i)).put("latitude", lat);
                    //根据经纬度查询详细地址
                    String formatted_address = MapUtil.getAddress(lng, lat);
                    ((JSONObject) companyArr.get(i)).put("formatted_address", formatted_address);
                }
            }
            for (int i = 0; i < companyArr.size(); i++) {
                JSONObject company = companyArr.getJSONObject(i);
                Map<String, Object> map = new LinkedHashMap<String, Object>();
                for (String key : company.keySet()) {
                    map.put(key, company.get(key));
                }
                page.add(map);
            }
            int recordcount = Integer.parseInt(companyObj.getString("total"));
            res.setRecordcount(recordcount);//总条数
            res.setPagecount(TianyanchaNew.getPageount(recordcount, pageSize0));//总页数
        } else {
            res.setPagecount(0);
            res.setRecordcount(0);
        }
        res.setPagesize(pageSize0);
        res.setPageid(pageNum0);
        res.setPage(page);
        res.setRetCode(0);
        res.setRetMessage("OK");
        return res;
    }

    public PageData getCompanyDetails(DataReq req) {
        PageData res = new PageData();
        String keyword = (String) req.getReqData().get("keyword");
        JSONObject companyObj = TianyanchaNew.baseinfoCompany(keyword);
        res.setExtData(companyObj);
        res.setRetCode(0);
        res.setRetMessage("OK");
        return res;
    }

    public PageData getCompanyChange(DataReq req) {
        PageData res = new PageData();
        String keyword = (String) req.getReqData().get("keyword");
        JSONObject companyObj = TianyanchaNew.getCompanyChange(keyword);
        res.setExtData(companyObj);
        res.setRetCode(0);
        res.setRetMessage("OK");
        return res;
    }

    public PageData getCompanyUser(DataReq req) {
        PageData res = new PageData();
        String keyword = (String) req.getReqData().get("keyword");
        JSONObject companyObj = TianyanchaNew.getCompanyUser(keyword);
        res.setExtData(companyObj);
        res.setRetCode(0);
        res.setRetMessage("OK");
        return res;
    }

}